﻿
using JWT;
using JWT.Algorithms;
using JWT.Exceptions;
using JWT.Serializers;
using Timo.Common.Extension;

namespace Timo.Common.Extension;

public static class JwtHelper
{
    private static string default_key { get; set; } = "a2022?01";
    private static string default_exp_time { get; set; } = (TimeHelper.GetTimeStamp() + 7200).ToString();

    /// <summary>
    /// 创建token
    /// </summary>
    /// <param name="payload">数据集</param>
    /// <param name="secret">密钥</param>
    /// <param name="extraHeaders"></param>
    /// <returns></returns>
    public static string CreateToken(IDictionary<string, object> payload, string? secret = null, IDictionary<string, object> extraHeaders = null)
    {
        var token = string.Empty;
        if(payload is null || payload == default(IDictionary<string, object>) || payload.Count<=0)
            return token;
        if (secret is null || string.IsNullOrEmpty(secret) || string.IsNullOrWhiteSpace(secret) || secret == default(string))
            secret = default_key;
        if (!payload.ContainsKey("exp"))
            payload.Add("exp", default_exp_time);
        IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
        IJsonSerializer serializer = new JsonNetSerializer();
        IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
        IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
        token = encoder.Encode(payload, secret);
        return token;
    }

    /// <summary>
    /// 解析token
    /// </summary>
    /// <param name="token"></param>
    /// <param name="secret"></param>
    /// <returns></returns>
    public static string ValidateToken(this string token, string? secret = null)
    {
        var json = string.Empty;
        if (token is null || string.IsNullOrEmpty(token) || string.IsNullOrWhiteSpace(token) || token == default(string))
            return json;
        if (secret is null || string.IsNullOrEmpty(secret) || string.IsNullOrWhiteSpace(secret) || secret == default(string))
            secret = default_key;
        try
        {
            IJsonSerializer serializer = new JsonNetSerializer();
            IDateTimeProvider provider = new UtcDateTimeProvider();
            IJwtValidator validator = new JwtValidator(serializer, provider);
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtAlgorithm alg = new HMACSHA256Algorithm();
            IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, alg);
            json = decoder.Decode(token, secret, true);                      
        }
        catch (TokenExpiredException)
        {
            //表示过期
            return "expired";
        }
        catch (SignatureVerificationException)
        {
            //表示验证不通过
            return "invalid";
        }
        catch (Exception)
        {
            return "error";
        }
        return json;
    }

}